package com.briup.day20;

public class Test_SyncMethod {
    //测试静态方法线程同步
    public static void main(String[] args) {
        Printer p = new Printer();
        Thread th1 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    p.print3();
                }
            }
        };
        Thread th2 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    p.print4();
                }
            }
        };
        th1.start();
        th2.start();
    }

    //测试普通方法线程同步
    public static void main01(String[] args) {
        Printer p = new Printer();
        Thread th1 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    p.print1();
                }
            }
        };
        Thread th2 = new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    p.print2();
                }
            }
        };
        th1.start();
        th2.start();
    }
}

class Printer {
    //普通同步方法，锁对象默认是this --->p
    public synchronized void print1() {
        System.out.print("好");
        System.out.print("好");
        System.out.print("学");
        System.out.print("习");
        System.out.println();
    }

    public void print2() {
        //synchronized (this) {
        //不是同一个锁对象
        synchronized (Printer.class) {
            System.out.print("天");
            System.out.print("天");
            System.out.print("向");
            System.out.print("上");
            System.out.println();
        }
    }

    //static静态同步方法: 锁对象默认为当前类字节码对象（Printer.class）
    public static synchronized void print3() {
        System.out.print("好");
        System.out.print("好");
        System.out.print("学");
        System.out.print("习");
        System.out.println();
    }

    public void print4() {
        synchronized (Printer.class) {
            System.out.print("天");
            System.out.print("天");
            System.out.print("向");
            System.out.print("上");
            System.out.println();
        }
    }
}